<?php
class XARRecord extends XAbstractModel{
	protected $dao = null;
	protected $saved = false;
	
	public function __construct() {
		$this->dao = XARDAO::dao(get_class($this));
	}
	
	/**
	 * @return XARQuery
	 */	
	public function getQuery() {
		return new XARQuery(get_class($this));
	}

	/**
	 * @return XARRecord
	 */	
	public function setDao(XDAO $dao){
		$this->dao = $dao;
		return $this;
	}
	
	/**
	 * @return XARDAO
	 */	
	public function dao(){
		return $this->dao;
	}
	
	/**
	 * @return XARRecord
	 */	
	public function setSaved($saved){
		$this->saved = $saved;
		return $this;
	}
	
	public function save(array $values = array()){
		if($this->saved){
			return $this->update($values);
		}
		return $this->insert($values);
	}
		
	public function insert(array $values = array()){
		$this->beforeCreated();
		$result = $this->dao()->insert($this, $values);
		if($result){			
			$this->saved = true;
			$this->afterCreated();
		}
		return $result;
	}
	
	public function update(array $values = array()){
		$this->beforeUpdated();
		$result = $this->dao()->update($this, $values);
		if($result){			
			$this->saved = true;
			$this->afterUpdated();
		}
		return $result;
	}
	
	public function remove(){
		$this->beforeRemoved();
		$result = $this->dao()->remove($this);
		if($result){			
			$this->saved = false;
			$this->afterRemoved();
		}
		return $result;
	}
	
	public function attrs(){
		return $this->asArray();
	}
	
	public function __get($key){
		$value = parent::__get($key);
		if(!is_null($value)){
			return $value;
		}
		//lazy load relations
		$value = $this->dao()->relation($this, $key);
		if(!is_null($value)){
			$this->$key = $value;
		}
		if(!isset($this->$key)){
			return null;
		}
		return $this->$key;
	}
	
	protected function beforeCreated(){
		
	}
	
	protected function afterCreated(){
		
	}

	protected function beforeUpdated(){
		
	}

	protected function afterUpdated(){
		
	}

	protected function beforeRemoved(){
		
	}

	protected function afterRemoved(){
		
	}
	
	public function beginTransaction(){
		return $this->dao()->driver()->beginTransaction();
	}
	
	public function isTransacting(){
		return $this->dao()->driver()->isTransacting();
	}	
	
	public function commit(){
		return $this->dao()->driver()->commit();
	}
		
	public function rollback(){
		return $this->dao()->driver()->rollback();
	}
}
?>